﻿using FlowServe.RemotingServer;
using Microsoft.Extensions.Hosting;
using System.ComponentModel;
using System.Reflection;
using System.Threading;

namespace FlowServe
{
    public class BackgroundTask : BackgroundService
    {
        //List<Type> methodInfos = new List<Type>();
        List<Action> queueTask = new List<Action>();
        private readonly IServiceProvider _services;

        public BackgroundTask(IServiceProvider _services)
        {
            this._services = _services;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {       
            var taskwork= GetAllSubclassesOfInterface("FlowServe.Work", typeof(IWorkGroupCenter));
            using var scope = _services.CreateScope();
            var taskWorkService = scope.ServiceProvider.GetRequiredService<IRemoting>();
            foreach (var task in taskwork)
            {
                try
                {
                    object myInstance = Activator.CreateInstance(task);
                    if(myInstance != null&& myInstance is IWorkGroupCenter)
                    {
                        queueTask.Add((myInstance as IWorkGroupCenter).Work);
                    }
                }catch (Exception ex)
                {

                    Console.WriteLine($"创建工作组失败：{ex.Message}");
                }             
            }
            //执行任务
            while (stoppingToken.CanBeCanceled)
            {
                if (taskWorkService.IsStartTask)
                {
                    taskWorkService.tiggerWork();
                }
                foreach (var item in queueTask)
                {                  
                   item.Invoke();
                }
                await Task.Delay(1000); // 模拟任务
            }

            Console.WriteLine("Background task stopped.");
        }
        private List<Type> GetAllSubclassesOfInterface(string namespaceName, Type interfaceType)
        {
            List<Type> types = new List<Type>();
            try
            {
                Assembly assembly = Assembly.GetExecutingAssembly();
                Type[] allTypes = assembly.GetTypes();
                foreach (var type in allTypes)
                {
                    if (type.Namespace == namespaceName && interfaceType.IsAssignableFrom(type) && type.IsClass && !type.IsAbstract)
                    {
                        types.Add(type);
                    }
                }
            }catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
         

            return types;
        }
    }
}
